package com.yc.store.servlet;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yc.store.bean.Goods;
import com.yc.store.mapper.GoodsMapper;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/4/25
 * Email haijunzhou@hnit.edu.cn
 */
@WebServlet("/queryGoods")
public class QueryGoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Goods good = new Goods();
        good.setName(req.getParameter("name"));
        good.setType(req.getParameter("type"));

        WebApplicationContext ioc=
                WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
        GoodsMapper goodsMapper = ioc.getBean(GoodsMapper.class);

        int pageNum = 1;
        int pageSize = 5;
        pageNum = Integer.valueOf(req.getParameter("pageNum"));
        pageSize = Integer.valueOf(req.getParameter("pageSize"));
        // page 即使查询的参数, 又是查询的结果
        IPage<Goods> page = new Page<>(pageNum, pageSize);
        List<Goods> goods = goodsMapper.select(good, page);
        // 手动的设置数据, spirng-boot 不需要这样操作
        page.setRecords(goods);
        resp.setContentType("application/json;charset=utf-8");
        Gson gson = new Gson();
        String json = gson.toJson(page);
        resp.getWriter().append(json);
    }
}
